package com.itheima.upload.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/upload.action")
@MultipartConfig
public class Upload  extends HttpServlet{
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //防乱码
        req.setCharacterEncoding("utf-8");
        //获取文件
        Part part = req.getPart("file");
        String filename = part.getSubmittedFileName();
        //以相对路径获取绝对路径
        String parth = getServletContext().getRealPath("/upload/"+new SimpleDateFormat("yyyyMM").format(new Date())) ;
        //System.out.println(parth);
        File f= new File(parth);
        //查看文件是否存在,不存在创建
        if (!f.exists()){
            f.mkdirs();
        }
        //获取文件的扩展名 .jpg
        String ext = filename.substring(filename.lastIndexOf("."),filename.length());
        long size = part.getSize();
        //UUID 命名法 名字36
//        String newname = UUID.randomUUID().toString()+"_"+ext;
//        System.out.println(newname);
        //Date+Random 时间 + 6位随机数

//        Date date = new Date();
        //格式化 日期
//        String dates = new SimpleDateFormat("yyyyMMddmmhhss").format(date);
//        Random random = new Random();
        //生成的新名字
//        String newname  = dates+"_"+String.format("%06d", random.nextInt(999999))+ext;
        if (ext.equals(".jpg")||ext.equals(".gif")||ext.equals(".png")){
            if (size<=3*1024*1024){
            String newname  = filename;
            File ff= new File(parth,newname);
            int i=0;
            //生成文件名（1）  （2）
            while (ff.exists()){
                newname = filename.substring(0,filename.lastIndexOf("."))+"("+ ++i +")"+ext ;//循环自增
                ff= new File(parth,newname);
            }
                part.write(parth+"/"+newname);

            }else {
                System.out.println("上传文件太大了");
            }

        }else {
            System.out.println("格式不正确");
        }

    }
}
